package com.cl.code.database.mybatis.module.result;


import java.util.Optional;
import java.util.function.Function;

/**
 * @author chengliang
 * @since 1.0.0
 */
public class SingleResultWrapper<Entity> {

    private final Entity instance;

    private SingleResultWrapper(Entity instance) {
        this.instance = instance;
    }

    public static <Entity> SingleResultWrapper<Entity> of(Entity instance) {
        return new SingleResultWrapper<>(instance);
    }

    public Optional<Entity> result() {
        return Optional.ofNullable(instance);
    }

    public <R> R result(Function<Entity, R> function) {
        return result(function, null);
    }

    public <R> R result(Function<Entity, R> function, R defaultValue) {
        if (result().isPresent()) {
            return function.apply(result().get());
        } else {
            return defaultValue;
        }
    }

}
